package com.example.myvideoplayer.Utils;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.example.myvideoplayer.Bean.Video;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static java.lang.System.out;

public class Untils {
    private static String thumbnailDir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Thumbnails";
    public static boolean isScanning = true;
    public static String formatTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        return formatter.format(new Date(time));
    }
    /**
     * 功能：扫描音频文件返回list
     *
     * @param context
     * @return musiclist
     */
    public static ArrayList<Video> scanAllAudioFiles(Context context) {
        File thumbnailFileDir = new File(thumbnailDir);
        if(!thumbnailFileDir.exists()){
            thumbnailFileDir.mkdir();
        }
        isScanning = true;
        ArrayList<Video> videoList = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                //视频文件路径
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                //视频编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                File file = new File(url);
                Log.d("555", "id :"+id+"  url"+url);
                if(!file.exists()){
                    File cover = new File(thumbnailDir+id+".jpg");
                    if(cover.exists()) {
                        cover.delete();
                    }
                    cursor.moveToNext();
                    continue; }
                //视频标题
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                //视频总时长
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                //视频文件大小
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));

                int width = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.WIDTH));
                int height = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.HEIGHT));
                Bitmap btImage = getBitmap(id);
                if(btImage == null){
                    btImage = getVideoThumbnail(url);
                    saveBitmap(id,btImage);
                }
                Video video = new Video();
                video.setName(title);
                video.setUrl(url);
                video.setDuration(duration);
                video.setSize(size / (1024 * 1024));
                video.setCover(btImage);
                videoList.add(video);
                Log.i("video_list", "title:" + title + " url:" + url );
                cursor.moveToNext();
            }
        }
        if (cursor != null) {
            cursor.close();
        }
        isScanning = false;
        return videoList;
    }

    /**
     * 给出url，获取视频的第一帧
     *
     * @param url
     * @return
     */
    public static Bitmap getVideoThumbnail(String url) {
        Bitmap bitmap = null;
        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一
        //的接口，用于从输入的媒体文件中取得帧和元数据；
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图
            retriever.setDataSource(url);
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }
    public static void saveBitmap(int id,Bitmap btImage){
        File thumb = new File(thumbnailDir,id+".jpg");
        try {
            FileOutputStream out = new FileOutputStream(thumb);
            if(btImage != null) {
                btImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            out.flush();
            out.close();
        }
    }
    public static Bitmap getBitmap(int id){
        File thumb = new File(thumbnailDir,id+".jpg");
        Bitmap bitmap = null;
        try {
            FileInputStream in = new FileInputStream(thumb);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static int Dp2Px(Context context, float dp) {
        //当前屏幕密度因子
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

}
